package com.auth.gateway.service;

import com.auth.gateway.model.LoginSession;
import com.auth.gateway.model.SystemLoginConfig;
import com.jayway.jsonpath.JsonPath;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;

@Component
public class TokenLoginStrategy implements LoginStrategy {

    private final WebClient webClient = WebClient.create();

    @Override
    public Mono<LoginSession> login(String userId, SystemLoginConfig config) {
        return webClient.post()
                .uri(config.getLoginUrl())
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(Map.of(
                        config.getUsernameParam(), userId,
                        config.getPasswordParam(), config.getStaticPassword()))
                .retrieve()
                .bodyToMono(String.class)
                .map(respBody -> {
                    String token = JsonPath.read(respBody, "$." + config.getTokenField());
                    LoginSession session = new LoginSession();
                    session.setSystemCode("legacy-b");
                    session.getHeaders().put(config.getHeaderName(), "Bearer " + token);
                    return session;
                });
    }
}